<!-- 利润表页面 -->
<template>
  <div class="padding" v-loading="loading">
    <el-card>
      <div slot="header" class="clearfix" v-if="$route.query.formula">
        <span class="text-df">利润表</span>
        <span class="text-sm">（公式可编辑保存）</span>
        <el-button style="padding: 3px 0" type="text" @click="recoverDefault(0)"
          >恢复系统默认设置</el-button
        >
      </div>
      <el-form
        v-if="!$route.query.formula"
        size="mini"
        class="padding-top-sm flex justify-between"
        :inline="true"
        :model="searchCriteria"
      >
        <el-form-item label="月份" prop="peroid">
          <el-date-picker
            type="month"
            style="width: 220px"
            v-model="searchCriteria.peroid"
            value-format="yyyy-MM"
            placeholder="请选择月份"
          ></el-date-picker>
        </el-form-item>
        <el-button-group>
          <el-button size="mini" type="primary" @click="query">查询</el-button>
          <el-button
            size="mini"
            type="warning"
            v-show="isShow"
            @click="exportTable"
            >导出.xls</el-button
          >
          <el-button size="mini" @click="openPage(0)">显示公式</el-button>
        </el-button-group>
      </el-form>
      <!-- 查询显示表格 -->
      <el-table
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        id="out-eltable"
        :data="tableData1"
        stripe
        class="text-sm"
        size="mini"
        v-if="!$route.query.formula"
      >
        <el-table-column type="index" width="50"></el-table-column>
        <ex-table-column
          :fit-header="true"
          :auto-fit="true"
          v-for="(item, index) in tableColumns1"
          :key="index"
          :label="item.label"
          :prop="item.prop"
        >
          <template slot-scope="scope">
            <div v-html="scope.row[item.prop]"></div>
          </template>
        </ex-table-column>
      </el-table>
      <!-- 显示公式表格 -->
      <el-table
        :data="tableData"
        stripe
        class="text-sm"
        size="mini"
        v-if="$route.query.formula"
      >
        <el-table-column type="index" width="50"></el-table-column>
        <ex-table-column
          :fit-header="true"
          :auto-fit="true"
          v-for="(item, index) in tableColumns"
          :key="index"
          :label="item.label"
          :prop="item.prop"
        >
          <template slot-scope="scope">
            <div
              v-html="scope.row[item.prop]"
              v-if="item.prop === 'A'"
              style="white-space: pre"
            ></div>
            <div
              v-html="scope.row[item.prop]"
              v-else-if="scope.$index === 0"
            ></div>
            <el-popover
              v-else
              placement="top-end"
              trigger="click"
              width="360"
              :ref="`popover${item.prop + scope.$index}`"
            >
              <el-row :gutter="10">
                <el-col :span="18">
                  <el-input
                    size="mini"
                    type="text"
                    v-model="scope.row[item.prop + 'g']"
                  >
                  </el-input
                ></el-col>
                <el-col :span="6" class="flex">
                  <el-button
                    size="mini"
                    type="success"
                    icon="el-icon-check"
                    circle
                    @click="saveOrUpdate(scope.$index, item.prop)"
                  ></el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-close"
                    circle
                    @click="changePop(scope.$index, item.prop)"
                  ></el-button>
                </el-col>
              </el-row>
              <span
                slot="reference"
                :class="{ 'text-red': !scope.row[item.prop] }"
                >{{
                  scope.row[item.prop] ? scope.row[item.prop] : "____"
                }}</span
              >
            </el-popover>
          </template>
        </ex-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<script>
import { ajax } from "@/store/yg/common/utils";
import { m } from "@/store/yg/common/local";
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  data() {
    return {
      isShow: false,
      loading: false,
      tableData: [],
      tableColumns: [],
      tableData1: [],
      tableColumns1: [],
      searchCriteria: {
        peroid: ""
      }
    };
  },
  mounted() {
    if (this.$route.query.formula) {
      this.showFormula(0);
    }
  },
  methods: {
    /*恢复默认*/
    recoverDefault(type = 0) {
      this.$confirm("确定是否要恢复默认值?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          var data = {};
          data["type"] = type;
          ajax("recoverDefault", data).then(
            res => {
              this.row = res;
              var success = res.success;
              if (!success) {
                this.$message.error(m(res.message));
                return;
              }
              this.$message({
                type: "success",
                message: "恢复成功!"
              });
            },
            error => {
              console.log(error);
              this.$message.error("请求内部发生异常");
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已经取消恢复"
          });
        });
    },
    /*修改单元格值*/
    saveOrUpdate(index, prop, type = 0) {
      const key = prop + (index + 1);
      console.log("key", key);
      const value = this.tableData[index][prop + "g"];
      console.log("value", value);
      if (null === key || "" === key) {
        this.$message.error("Key值为空");
        return;
      }
      var data = {};
      data["type"] = type;
      data["key"] = key;
      data["value"] = value;
      ajax("saveOrUpdate", data).then(
        res => {
          this.row = res;
          var success = res.success;
          if (!success) {
            this.$message.error(m(res.message));
            return;
          }
          this.$message({
            type: "success",
            message: "保存成功!"
          });
          this.tableData[index][prop] = value;
        },
        error => {
          console.log(error);
        }
      );
    },
    // 新开页面
    openPage() {
      window.open("/#/blank/finance__profit__main?formula=1");
    },
    /*显示公式事件*/
    showFormula(type = 0) {
      if ("" === type) {
        this.$message.error("未知的类型!");
        return;
      }
      if (0 !== type) {
        this.$message.error("类型非法!");
        return;
      }
      var data = {};
      data["type"] = type;
      ajax("showFormula", data).then(
        res => {
          this.row = res;
          var entry = res.entry;
          if (null === entry || undefined == entry || "" === entry) {
            this.$message.error("加载公式失败，可能是模板不存在");
          }
          entry = JSON.parse(entry);
          console.log("entry", entry);
          /*行*/
          var cols = entry.cols;
          const col = [];
          for (const i of entry.cols) {
            col.push({
              prop: i,
              label: i
            });
          }
          this.tableColumns = col;
          const row = [];
          for (const i of entry.rows) {
            let obj = {};
            for (const j of entry.cols) {
              obj[j] = entry.colrowFormatMap[j + i];
              obj[j + "g"] = entry.colrowFormatMap[j + i];
            }
            row.push(obj);
          }
          console.log("row", row);
          this.tableData = row;
          /*列*/
          var rows = entry.rows;
          /*行列值*/
          var colrowFormatMap = entry.colrowFormatMap;
          if (cols === 0 || rows === 0) {
            this.$message.error("模板数据非法!");
            return;
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    /**/
    query() {
      const peroid = this.searchCriteria.peroid;
      if (!peroid) {
        this.$message.error("请选择月份!");
        return;
      }
      var data = {};
      this.tableData1 = [];
      this.tableColumns1 = [];
      data["peroid"] = peroid;
      this.loading = true;
      ajax("query", data).then(
        res => {
          console.log(res);
          const col = [];
          for (const i of res.format.cols) {
            col.push({
              prop: i,
              label: i
            });
          }
          this.tableColumns1 = col;
          const row = [];
          const list = { ...res.format.colrowFormatMap, ...res.calculationMap };
          for (const i of res.format.rows) {
            let obj = {};

            for (const j of res.format.cols) {
              obj[j] = list[j + i];
            }
            row.push(obj);
          }
          this.tableData1 = row;
          this.isShow = true;
          this.loading = false;
        },
        error => {
          console.log(error);
        }
      );
    },
    //导出
    exportTable() {
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(document.querySelector("#out-eltable"));
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          "利润表.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    changePop(index, prop) {
      this.tableData[index][prop + "g"] = this.tableData[index][prop];
      this.$refs[`popover${prop + index}`][0].showPopper = false;
    }
  }
};
</script>
